package com.avecsys.quotemanager.mbeans.security;

import java.io.Serializable;

import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.avecsys.quotemanager.constants.ApplicationConstants;
import com.avecsys.quotemanager.dao.common.EnumActor;
import com.avecsys.quotemanager.dao.common.EnumTransactionStatus;
import com.avecsys.quotemanager.exception.BusinessException;
import com.avecsys.quotemanager.mbeans.core.BaseMBean;
import com.avecsys.quotemanager.pojos.UserMasterPojo;
import com.avecsys.quotemanager.service.security.LoginService;
import com.avecsys.quotemanager.utils.MessageBoardUtil;
import com.avecsys.quotemanager.utils.TransactionStatus;
import com.icesoft.faces.context.effects.JavascriptContext;

/**
 * @author Sam Sundar K
 * 
 */
public class LoginMBean extends BaseMBean implements Serializable {

	private final Log log = LogFactory.getLog(LoginMBean.class);

	private UserMasterPojo userMasterPojo = new UserMasterPojo();

	private LoginService loginService;

	private String loggedInUserName;

	private String lastLoginTime;

	/**
	 * Method to authenticate the user credentials
	 * 
	 * @return String Navigation OutCome
	 */
	public String actionAuthenticate() {
		String navigationOutCome = "openLoginScreen";
		try {
			TransactionStatus transactionStatus = loginService
					.authenticate(userMasterPojo);
			MessageBoardUtil.publishTransactionStatusMessage(transactionStatus,
					EnumActor.SUPPLIER, "messageBoardId", "", null);
			if (transactionStatus.getStatus().intValue() == EnumTransactionStatus.READ_SUCCESS
					.ordinal()) {
				setLoggedInUserName(getSignedInUser().getUserName());
				navigationOutCome = "openHomeScreen";
			} else {
				userMasterPojo = new UserMasterPojo();
			}
		} catch (BusinessException e) {
			log.error(e);
		}
		return navigationOutCome;
	}

	public String getLastLoginTime() {
		return lastLoginTime;
	}

	public String getLoggedInUserName() {
		return loggedInUserName;
	}

	public LoginService getLoginService() {
		return loginService;
	}

	public UserMasterPojo getUserMasterPojo() {
		return userMasterPojo;
	}

	public void isUserSignedIn() {
		if (getSignedInUser() == null || !getSignedInUser().isPersisted()) {
			actionLogout(null);
		}
	}

	public void setLastLoginTime(String lastLoginTime) {
		this.lastLoginTime = lastLoginTime;
	}

	public void setLoggedInUserName(String loggedInUserName) {
		this.loggedInUserName = loggedInUserName;
	}

	public void setLoginService(LoginService loginService) {
		this.loginService = loginService;
	}

	public void setUserMasterPojo(UserMasterPojo userMasterPojo) {
		this.userMasterPojo = userMasterPojo;
	}
}
